

package com.zdkj.subway.rca.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.rca.entity.SwAuStationTicketDifferenceDto;
import com.zdkj.subway.rca.entity.SwCkBankCashPaymentNote;
import com.zdkj.subway.rca.enums.DEL_FLAG;
import com.zdkj.subway.rca.enums.SW_CK_BANK_CASH_PAYMENT_NOTE_DATA_SOURCE;
import com.zdkj.subway.rca.exceptions.BizException;
import com.zdkj.subway.rca.service.SwAuStationTicketDifferenceDtoService;
import com.zdkj.subway.rca.service.SwCkBankCashPaymentNoteService;
import com.zdkj.subway.rca.util.JdbcUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 银行现金缴款单
 *
 * @author cooze
 * @date 2020-10-18 17:26:59
 */
@RestController
@AllArgsConstructor
@RequestMapping("/swckbankcashpaymentnote")
@Api(value = "swckbankcashpaymentnote", tags = "银行票据单管理-银行现金缴款单管理")
public class SwCkBankCashPaymentNoteController extends SwCkBankCashPaymentNoteBaseController {

    private final SwCkBankCashPaymentNoteService swCkBankCashPaymentNoteService;
    private final SwAuStationTicketDifferenceDtoService swAuStationTicketDifferenceDtoService;


    /**
     * 获取所有的地铁线路
     *
     * @return 出参
     */
    //@ApiOperation(tags = {"银行票据单管理-银行现金缴款单管理","清分及划账-系统清分数据对比","清分及划账-导入系统清分数据展示"},value = "查询地铁线路", notes = "查询地铁线路")
    @ApiOperation(tags = {"银行票据单管理-银行现金缴款单管理","清分及划账-导入系统清分数据展示"},value = "查询地铁线路", notes = "查询地铁线路")
    @GetMapping("/listAllSubWayLine")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "dataType", value = "数据类型：1-银行单据数据（短周期地铁线路）、2-长周期结算（长周期地铁线路） (备注：为空时则查出所有地铁线路 )", dataTypeClass = String.class)
            }
    )
    public R listAllSubWayLine(String dataType) {
        return R.ok(swCkBankCashPaymentNoteService.listAllSubWayLineByDataType(dataType));
    }

    /**
     * 查询地铁线路下的所有站点
     *
     * @param lineCode 地铁线路
     * @return 出参
     */
    @ApiOperation(value = "查询地铁线路下的站点", notes = "查询地铁线路下的站点")
    @GetMapping("/listSubWayStation")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "dataType", value = "数据类型：1-银行单据数据（短周期站点）、2-长周期结算（长周期站点） (备注：为空时则查出所有站点 )", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "lineCode", value = "线路编码", dataTypeClass = String.class)
            }
    )
    public R listSubWayStationByLineCode(String dataType, String lineCode) {
        return R.ok(swCkBankCashPaymentNoteService.listSubWayStationByLineCodeAndDataType(lineCode, dataType));
    }


    /**
     * 分页查询
     *
     * @param page        分页对象
     * @param lineCode    线路编码
     * @param stationCode 车站编码
     * @param startDate   开始日期：yyyy-MM-dd
     * @param endDate     结束日期：yyyy-MM-dd
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "lineCode", value = "线路编码", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "stationCode", value = "车站编码", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "startDate", value = "开始日期：yyyy-MM-dd", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "endDate", value = "结束日期：yyyy-MM-dd", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "executeStatus", value = "操作状态", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "tradeTime", value = "交易日期：yyyy-MM-dd", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "diffCondition", value = "差异条件", dataTypeClass = String.class)
            }
    )
    public R getSwCkBankCashPaymentNotePage(Page page,String lineCode,String stationCode,String startDate,String endDate,String tradeTime,String executeStatus,String diffCondition) {
         //车站用户查询 只查本车站的数据 20241031
		 if (!SecurityUtils.getUser().getBelongToLine()&&!"".equals(SecurityUtils.getUser().getStationCode())) {
			lineCode = SecurityUtils.getUser().getLineCode();
			stationCode =SecurityUtils.getUser().getStationCode();	
			executeStatus = "1";			
		  }
		IPage<SwCkBankCashPaymentNote> swCkBankCashPaymentNoteList =  swCkBankCashPaymentNoteService.getSwCkBankCashPaymentNote(page,lineCode, stationCode,startDate,endDate,tradeTime,executeStatus,diffCondition);
        return R.ok(swCkBankCashPaymentNoteList);
        /*SwCkBankCashPaymentNote swCkBankCashPaymentNote = new SwCkBankCashPaymentNote();
        swCkBankCashPaymentNote.setDelFlag(DEL_FLAG.NO.getCode());
        if (StringUtils.isNotEmpty(lineCode)) {
            swCkBankCashPaymentNote.setLineCode(lineCode);
        }
        if (StringUtils.isNotEmpty(stationCode)) {
            swCkBankCashPaymentNote.setStationCode(stationCode);
        }
        if (StringUtils.isNotEmpty(executeStatus)) {
            swCkBankCashPaymentNote.setExecuteStatus(executeStatus);
        }
        if (StringUtils.isNotEmpty(tradeTime)) {
            LocalDate tradeTimeLocalDate = LocalDate.parse(tradeTime, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            swCkBankCashPaymentNote.setTradeTime(tradeTimeLocalDate);
        }
        //开始时间<=入账开始时间<=结束时间 and 开始时间<=入账结束时间<=结束时间
//        return R.ok(
//                swCkBankCashPaymentNoteService.page(page, Wrappers.query(swCkBankCashPaymentNote)
//                        .lambda().ge(StringUtils.isNotEmpty(startDate), SwCkBankCashPaymentNote::getEntryStartTime, startDate).le(StringUtils.isNotEmpty(endDate), SwCkBankCashPaymentNote::getEntryStartTime, endDate)
//                        .ge(StringUtils.isNotEmpty(startDate), SwCkBankCashPaymentNote::getEntryEndTime, startDate).le(StringUtils.isNotEmpty(endDate), SwCkBankCashPaymentNote::getEntryEndTime, endDate))
//        );
        boolean isDateCondition = StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate);
        return R.ok(
                swCkBankCashPaymentNoteService.page(page, Wrappers.query(swCkBankCashPaymentNote)
                        .lambda().between(isDateCondition, SwCkBankCashPaymentNote::getEntryStartTime, startDate, endDate)
                        .between(isDateCondition, SwCkBankCashPaymentNote::getEntryStartTime, startDate, endDate)
                        .orderByDesc(SwCkBankCashPaymentNote::getTradeTime))
        );*/
    }


    /**
     * 通过id查询银行现金缴款单
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(swCkBankCashPaymentNoteService.getById(id));
    }

    /**
     * 新增银行现金缴款单
     *
     * @param swCkBankCashPaymentNote 银行现金缴款单
     * @return R
     */
    @ApiOperation(value = "新增银行现金缴款单", notes = "新增银行现金缴款单")
    @SysLog("新增银行现金缴款单")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('rca_swckbankcashpaymentnote_add')")
    public R save(@RequestBody SwCkBankCashPaymentNote swCkBankCashPaymentNote) {
        swCkBankCashPaymentNote.setDataSource(SW_CK_BANK_CASH_PAYMENT_NOTE_DATA_SOURCE.ENTER_MANUALLY.getCode());
        try {
            PigxUser pigxUser = SecurityUtils.getUser();
            swCkBankCashPaymentNote.setCreatorId(pigxUser.getId());
            swCkBankCashPaymentNote.setCreatorName(pigxUser.getNikeName());
            swCkBankCashPaymentNote.setCreateTime(LocalDateTime.now());
            swCkBankCashPaymentNote.setDelFlag(DEL_FLAG.NO.getCode());
            LocalDate entryStartTime = swCkBankCashPaymentNote.getEntryStartTime();
            LocalDate entryEndTime = swCkBankCashPaymentNote.getEntryEndTime();
            //添加非长周期车站数据时，开始时间和结束时间获取的是当前时间，改成获取收益时间。
            if(entryStartTime == null || entryEndTime == null){
                swCkBankCashPaymentNote.setEntryStartTime(swCkBankCashPaymentNote.getTradeTime());
                swCkBankCashPaymentNote.setEntryEndTime(swCkBankCashPaymentNote.getTradeTime());
            }
            return R.ok(swCkBankCashPaymentNoteService.save(swCkBankCashPaymentNote));
        } catch (BizException e) {
            return R.failed("数据已存在");
        }
    }

    /**
     * 修改银行现金缴款单
     *
     * @param swCkBankCashPaymentNote 银行现金缴款单
     * @return R
     */
    @ApiOperation(value = "修改银行现金缴款单", notes = "修改银行现金缴款单")
    @SysLog("修改银行现金缴款单")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('rca_swckbankcashpaymentnote_edit')")
    public R updateById(@RequestBody SwCkBankCashPaymentNote swCkBankCashPaymentNote) {
        swCkBankCashPaymentNote.setDataSource(SW_CK_BANK_CASH_PAYMENT_NOTE_DATA_SOURCE.ENTER_MANUALLY.getCode());
        return R.ok(swCkBankCashPaymentNoteService.updateById(swCkBankCashPaymentNote));
    }

    /**
     * 批量删除银行现金缴款单
     *
     * @param ids 批量删除银行现金缴款单
     * @return R
     */
    @ApiOperation(value = "批量删除银行现金缴款单", notes = "批量删除银行现金缴款单")
    @SysLog("批量删除银行现金缴款单")
    @DeleteMapping("/delBatch")
    public R removeBatch(@RequestBody List<Integer> ids) {
        return R.ok(swCkBankCashPaymentNoteService.removeByIds(ids));
    }

    /**
     * @param dataType    "数据类型：1-银行单据数据、2-长周期结算"
     * @param lineCode    "线路编码"
     * @param stationCode "车站编码"
     * @param tradeTime   "交易日期：yyyy-MM-dd"
     * @return 出参
     */
    @ApiOperation(value = "补卸载金额 和 补短款金额 查询", notes = "补卸载金额 和 补短款金额 查询")
    @GetMapping("/getUnloadShortAmount")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(required = true, name = "dataType", value = "数据类型：1-银行单据数据、2-长周期结算", dataTypeClass = String.class),
                    @ApiImplicitParam(required = true, name = "lineCode", value = "线路编码", dataTypeClass = String.class),
                    @ApiImplicitParam(required = true, name = "stationCode", value = "车站编码", dataTypeClass = String.class),
                    @ApiImplicitParam(required = true, name = "tradeTime", value = "交易日期：yyyy-MM-dd", dataTypeClass = String.class)
            }
    )
    public R getUnloadShortAmount(String dataType, String lineCode,
                                  String stationCode,String tradeTime) {
        Optional<R> error = baseValidate(dataType, lineCode, stationCode,tradeTime);
        return error.orElseGet(() -> R.ok(swCkBankCashPaymentNoteService.getUnloadShortAmount(dataType, lineCode, stationCode,tradeTime)));
    }

    /**
     * @param startDate   开始日期：yyyy-MM-dd
     * @param endDate     结束日期：yyyy-MM-dd
    * @return 出参
     */
    @ApiOperation(value = "生成车站票款差异", notes = "生成车站票款差异")
    @GetMapping("/getGenerateStationFareDifference")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "startDate", value = "开始日期：yyyy-MM-dd", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "endDate", value = "结束日期：yyyy-MM-dd", dataTypeClass = String.class)
            }
    )
    public R getGenerateStationFareDifference(String startDate, String endDate) throws SQLException {

        boolean isDateCondition = StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate);
        if(isDateCondition){
            LocalDate startDateLocalDate = LocalDate.parse(startDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            LocalDate endDateLocalDate = LocalDate.parse(endDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            //查询有差异的数据进行合并整理
            List<Map<String, Object>> list = swCkBankCashPaymentNoteService.getSwStReportqueryStationincomeList(startDate, endDate);

            ArrayList<SwAuStationTicketDifferenceDto> arrayList = new ArrayList<>();
            PigxUser user = SecurityUtils.getUser();
            if(list.size()>0){
                list.forEach(item -> {
                    SwAuStationTicketDifferenceDto swAuStationTicketDifferenceDto = new SwAuStationTicketDifferenceDto();

                    QueryWrapper<SwAuStationTicketDifferenceDto> wrapper = new QueryWrapper<>();
                    wrapper.lambda().eq(SwAuStationTicketDifferenceDto::getLineCode,item.get("LINE_CODE").toString());
                    wrapper.lambda().eq(SwAuStationTicketDifferenceDto::getStationCode,item.get("STATION_CODE").toString());
                    wrapper.lambda().eq(SwAuStationTicketDifferenceDto::getIncomeTime,(Date) item.get("INCOME_TIME"));
                    SwAuStationTicketDifferenceDto one = swAuStationTicketDifferenceDtoService.getOne(wrapper);
                    boolean isJump = true;
                    if(one!=null){
                        String settleStatus = one.getSettleStatus();
                        if("1".equals(settleStatus)){
                            isJump = false;
                        }
                        swAuStationTicketDifferenceDto.setId(one.getId());
                        swAuStationTicketDifferenceDto.setUpdateTime(new Date());
                    }
                    if(isJump){
                        swAuStationTicketDifferenceDto.setLineCode(item.get("LINE_CODE").toString());
                        swAuStationTicketDifferenceDto.setStationCode(item.get("STATION_CODE").toString());
                        swAuStationTicketDifferenceDto.setConductorJobNo(String.valueOf(item.get("CONDUCTOR_JOB_NO")));
                        swAuStationTicketDifferenceDto.setConductorPersonName(String.valueOf(item.get("CONDUCTOR_PERSON_NAME")));
                        swAuStationTicketDifferenceDto.setIncomeTime((Date) item.get("INCOME_TIME"));
                        swAuStationTicketDifferenceDto.setSettleBeginDate((Date) item.get("SETTLE_BEGIN_DATE"));
                        swAuStationTicketDifferenceDto.setSettleEndDate((Date) item.get("SETTLE_END_DATE"));
                        swAuStationTicketDifferenceDto.setCashPayAmount((BigDecimal) item.get("CASH_PAY_AMOUNT"));//现金缴款单金额
                        swAuStationTicketDifferenceDto.setCashReceiptsAmount((BigDecimal) item.get("CASH_RECEIPTS_AMOUNT"));//车站营收日报
						swAuStationTicketDifferenceDto.setShortAmount((BigDecimal) item.get("SHORT_AMOUNT"));//补短款
                        swAuStationTicketDifferenceDto.setDiffAmount((BigDecimal) item.get("DIFF_AMOUNT"));
                        swAuStationTicketDifferenceDto.setIsAddNotice("0");
                        swAuStationTicketDifferenceDto.setDataSource("1");
                        swAuStationTicketDifferenceDto.setSettleStatus("0");
                        swAuStationTicketDifferenceDto.setCreatorId(user.getId());
                        swAuStationTicketDifferenceDto.setCreatorName(user.getNikeName());
                        swAuStationTicketDifferenceDto.setCreateTime(new Date());
                        arrayList.add(swAuStationTicketDifferenceDto);
                    }

                });
            }
            if(arrayList.size()>0){
                boolean isTrue = swAuStationTicketDifferenceDtoService.saveOrUpdateBatch(arrayList);
                if(isTrue){
                    String sql="update\n" +
                            "            sw_ck_bank_cash_payment_note scb, sw_st_reportquery_stationincome sss\n" +
                            "        set\n" +
                            "            scb.EXECUTE_STATUS = '1'\n" +
                            "        where\n" +
                            "            scb.LINE_CODE = sss.LINE_CODE\n" +
                            "            and scb.STATION_CODE = sss.STATION_CODE\n" +
                            "            and scb.TRADE_TIME = sss.STATISTICS_DATE\n" +
                            "            and sss.STATISTICS_DATE >= '"+startDateLocalDate+"'\n" +
                            "            and sss.STATISTICS_DATE <= '"+endDateLocalDate+"'";
                    JdbcUtil.exeSqlCrud(sql);
                    //swCkBankCashPaymentNoteService.updateExecuteStatus(startDateLocalDate,endDateLocalDate);
                }
                return R.ok("生成成功！");
            }else {
                return R.failed("没有可生成的数据！");
            }
        }
        return R.ok();
    }

}
